/**
 * 
 * @param {Map} map 
 * 将Map类型转换为对象数组，用于echarts词云插件
 */
function mapToArray(map) {
    const arr = Array.from(map)
    const res = []
    arr.map(item => {
        const obj = {}
        obj.name = item[0]
        obj.value = item[1]
        res.push(obj)
    })
    return res
}

/**
 * 
 * @param {Array} params 
 * @param {Map} map 
 */
function setCloudWords(params, map) {
    const res = map
    if(params && params[0]) {
        const welfs = params
        for(let j = 0; j < welfs.length; j++) {
            if(!res.get(welfs[j])) {
                res.set(welfs[j], 1)
            } else {
                const value = res.get(welfs[j]) + 1
                res.set(welfs[j], value)
            }
        }
    }
    return res
}

function setSingleWords(params, map) {
    const company = params
    const res = map
    if(company) {
        if(!res.get(company)) {
            res.set(company, 1)
        } else {
            const value = res.get(company) + 1
            res.set(company, value)
        }
    }
    return res
}

const charset = require('superagent-charset');
const superagent = charset(require('superagent'));
/**
 * 
 * @param {String} BASE_URL 
 * @param {Array} paramList 
 * @param {Number} syncLimit
 * @param {Number} pageLimit 
 */
function asyncFetch(BASE_URL, paramList, syncLimit, pageLimit, headers) {
    return new Promise(async (resolve, reject) => {
        let syncNumber = 0
        while(paramList) {
           const res = await superagent.get(`${BASE_URL}/${paramList.pop()}/`).charset('utf8').set(headers)
           await sleep(500)
        }
        resolve(true)
    })
}

function sleep (time) {
    return new Promise((resolve) => setTimeout(resolve, time));
  }

module.exports = {
    mapToArray,
    setCloudWords,
    asyncFetch,
    sleep,
    setSingleWords
}